package xyx.chenweb.myapp.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import xyx.chenweb.myapp.RoleEnum.MyRole;
import xyx.chenweb.myapp.entity.UserInfo;
import xyx.chenweb.myapp.entity.UserRole;
import xyx.chenweb.myapp.mapper.mapping.UserInfoMapping;
import xyx.chenweb.myapp.mapper.mapping.UserRoleMapping;
import xyx.chenweb.myapp.utils.MyResponseData;
import xyx.chenweb.myapp.utils.MyTools;
import xyx.chenweb.myapp.utils.RanUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApiService {

    @Autowired
    private UserInfoMapping userInfoMapping;

    @Autowired
    private UserRoleMapping userRoleMapping;

    @Autowired
    @Lazy
    private EhcacheService ehcacheService;

    public MyResponseData login(String account, String password, String verifyCode){
        MyResponseData myResponseData = new MyResponseData();
        Subject subject = SecurityUtils.getSubject();
        String code = subject.getSession().getAttribute("code").toString();
        if(MyTools.isNotEmpty(verifyCode)){
            verifyCode = verifyCode.toUpperCase();
            code = code.toUpperCase();
            if(!code.equals(verifyCode)){
                myResponseData.setCode(500);
                myResponseData.setMessage("验证码不正确！");
                return myResponseData;
            }
        }else{
            myResponseData.setCode(500);
            myResponseData.setMessage("验证码为空！");
            return myResponseData;
        }

        try{
            subject.login(new UsernamePasswordToken(account, password));
        }catch (UnknownAccountException e){ //用户名错误
            myResponseData.setCode(500);
            myResponseData.setMessage("账号错误");
            return myResponseData;
        }catch (IncorrectCredentialsException e){
            myResponseData.setCode(500);
            myResponseData.setMessage("密码错误");
            return myResponseData;
        }

        Map result = new HashMap();
        result.put("account", account);
        QueryWrapper <UserRole>queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", account);
        UserRole userRole = userRoleMapping.selectOne(queryWrapper);
        if(MyTools.isEmpty(userRole)){
            result.put("role", MyRole.VISITOR.value);
        }else{
            result.put("role", userRole.getRole());
        }

        //在缓存中添加用户信息
        UserInfo userInfo = userInfoMapping.selectById(account);
        userInfo.setUserPwd(result.get("role").toString()); //将密码的位子换为用户的角色
        userInfo.setUserSalt("");
        ehcacheService.saveUser(userInfo, userInfo.getUserId());

        myResponseData.setCode(200);
        myResponseData.setMessage("成功登录");
        myResponseData.setData(result);
        return myResponseData;
    }

    public MyResponseData register(String phone, String name, String pwd,
                                   String verifyCode, String sex, String birthday,
                                   String email, String addr, String qq, String wx){
        MyResponseData myResponseData = new MyResponseData();
        Subject subject = SecurityUtils.getSubject();
        String code = subject.getSession().getAttribute("code").toString();
        if(MyTools.isEmpty(verifyCode)){
            myResponseData.setCode(500);
            myResponseData.setMessage("验证码为空");
            return myResponseData;
        }else{
            verifyCode = verifyCode.toUpperCase();
            code = code.toUpperCase();
            if(!verifyCode.equals(code)){
                myResponseData.setCode(500);
                myResponseData.setMessage("验证码错误");
                return myResponseData;
            }
        }

        UserInfo oldUser = userInfoMapping.selectById(phone);
        if(oldUser != null){
            myResponseData.setCode(500);
            myResponseData.setMessage("该手机号码已经被注册");
            return myResponseData;
        }

        String salt = RanUtils.randomString(6);
        Md5Hash md5Hash = new Md5Hash(pwd, salt, 1024);
        String password = md5Hash.toHex();
        UserInfo userInfo = new UserInfo();

        userInfo.setUserPhone(phone);
        userInfo.setUserId(phone);
        userInfo.setUserSalt(salt);
        userInfo.setUserAddr(addr);
        userInfo.setUserPwd(password);
        userInfo.setUserStatus(2);
        userInfo.setUserQQ(qq);
        userInfo.setUserSex(sex);
        userInfo.setUserBirthday(birthday);
        userInfo.setUserEmail(email);
        userInfo.setUserName(name);
        userInfo.setUserWx(wx);
        userInfoMapping.insert(userInfo);

        UserRole userRole = new UserRole();
        userRole.setAccount(userInfo.getUserId());
        userRole.setRole(MyRole.VISITOR.value);
        userRoleMapping.insert(userRole);

        myResponseData.setCode(200);
        myResponseData.setMessage("成功注册");
        return myResponseData;
    }

    /**
     * 退出登录
     * @return
     */
    public MyResponseData logout(){
        MyResponseData myResponseData = new MyResponseData();
        Subject subject = SecurityUtils.getSubject();
        String id = subject.getPrincipal().toString();
        subject.logout();
        ehcacheService.deleteUser(id);
        myResponseData.setMessage("退出登录成功");
        myResponseData.setCode(200);
        return myResponseData;
    }

}
